package com.framework.service.admin.system;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.framework.common.BaseServiceSupport;
import com.framework.dao.admin.system.UserDao;
import com.framework.entity.admin.system.User;
import com.framework.entity.admin.system.UserExample;
import com.framework.util.Digests;
import com.framework.util.Encodes;
import com.framework.vo.IResult;
import com.framework.vo.Result;

@Service
@Transactional
public class UserService extends BaseServiceSupport<User, UserExample, UserDao, Integer> {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private UserDao userDao;

	@Override
	protected UserDao getDao() {
		return userDao;
	}

	@Override
	public IResult<Integer> saveOrUpdate(User record) {
		try {
			Serializable id = BeanUtils.getProperty(record, "id");
			if (StringUtils.isNotBlank(record.getPlainPassword())) {
				entryptPassword(record);
			}
			if (id != null) {
				int result = getDao().updateByPrimaryKey(record);
				if (result > 0) {
					return Result.createSuccess(result);
				} else {
					return Result.createFail();
				}
			} else {
				return this.save(record);
			}

		} catch (Exception e) {
			logger.error("saveOrUpdate fail ", e);
			return Result.createFail();
		}

	}

	public User findUserByUserName(String userName) {
		UserExample example = new UserExample();
		example.createCriteria().andUserNameEqualTo(userName).andDeleteMarkEqualTo(false);
		List<User> list = userDao.selectByExample(example);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
}